import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { successResponse, errorResponse } from '@/lib/response';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import { CreateContentRequest } from '@/types/content';

async function handler(req: NextRequest) {
  const authResult = await authenticateRequest(req);
  if (!authResult.success) {
    return errorResponse(authResult.error || '身份验证失败');
  }

  const { categoryIds, isBanner, type, ...data } = (await req.json()) as CreateContentRequest & {
    categoryIds: string[];
  };

  const createdContent = await prisma.content.create({
    data: {
      coverId: data.coverId,
      content: data.content,
      summary: data.summary,
      title: data.title,
      url: data.url, // 新增：保存站点地址
      isBanner,
      type,
      categories: {
        create: (categoryIds || []).map((id: string) => ({ categoryId: id }))
      }
    },
    include: { cover: true }
  });

  return successResponse(createdContent, '创建成功');
}

export const POST = withMiddleware(handler);